package top.as.sean.api.config;

import java.util.HashMap;
import java.util.Map;

/**
 * 用于封装当前用户信息
 *
 * @author: ArchieSean
 * @create: 2022/11/5
 */
public class UserHandler {
    /**
     * 用户名
     */
    public static final String USER_NAME = "username";
    /**
     * 账号
     */
    public static final String USER_ID = "userId";
    /**
     * 创建当前线程对象
     */
    private static final InheritableThreadLocal<Map<String, Object>> THREAD_LOCAL = new InheritableThreadLocal<>();

    private UserHandler() {
    }

    /**
     * 清除当前线程用户信息
     */
    public static void remove() {
        THREAD_LOCAL.remove();
    }

    /**
     * 设置缓存
     */
    public static void setMap(Map<String, Object> map) {
        THREAD_LOCAL.set(map);
    }

    /**
     * 获取缓存数据.
     *
     * @param key key
     * @return obj
     */
    public static Object get(String key) {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new HashMap<>(10);
            THREAD_LOCAL.set(map);
        }
        return map.get(key);
    }

    /**
     * 用户名
     *
     * @return str
     */
    public static String getUserName() {
        Object value = get(USER_NAME);
        return value == null ? "system" : value.toString();
    }
}
